package org.patchca;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;

import org.patchca.service.Captcha;

public class PatchcaDemoGUI extends JDialog implements ActionListener {

	private static final long	serialVersionUID	= 6698906953413370733L;
	private BufferedImage		img;
	private final JButton		reloadButton;

	public PatchcaDemoGUI() {
		super.setTitle("Patchca demo");
		this.setResizable(false);
		this.setSize(500, 200);
		Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
		int x = (dim.width - this.getSize().width) / 2;
		int y = (dim.height - this.getSize().height) / 2;
		this.setLocation(x, y);
		JPanel bottom = new JPanel();
		this.reloadButton = new JButton("Next");
		this.reloadButton.addActionListener(this);
		bottom.add(this.reloadButton);
		this.add(BorderLayout.SOUTH, bottom);
		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent we) {
				PatchcaDemoGUI.this.dispose();
			}
		});
	}

	@Override
	public void update(Graphics g) {
		this.paint(g);
	}

	@Override
	public void paint(Graphics g) {
		if (this.img == null) {
			this.createImage();
		}
		if (this.img != null) {
			g.drawImage(this.img, 20, 30, this);
		}
	}

	public void createImage() {
		// Captcha captcha = new ConfigurableCaptchaService().getCaptcha();
		Captcha captcha = IdiomsPatchca.next();
		if (captcha.getWord().equals(captcha.getChallenge())) {
			this.setTitle(captcha.getTips() + " 答:" + captcha.getChallenge());
		} else {
			this.setTitle(captcha.getTips() + " 问:" + captcha.getWord() + " 答:" + captcha.getChallenge());
		}

		this.img = captcha.getImage();
	}

	@Override
	public void actionPerformed(ActionEvent evt) {
		if (evt.getSource() == this.reloadButton) {
			this.createImage();
			this.repaint();
		}

	}

	public static void main(String[] args) {
		PatchcaDemoGUI f = new PatchcaDemoGUI();
		f.setVisible(true);
	}

}
